package by.msokoloff.javaweb2015.services.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.springframework.stereotype.Service;

import by.msokoloff.javaweb2015.dataaccess.CountryDao;
import by.msokoloff.javaweb2015.datamodel.City;
import by.msokoloff.javaweb2015.datamodel.City_;
import by.msokoloff.javaweb2015.datamodel.Country;
import by.msokoloff.javaweb2015.services.CityService;
import by.msokoloff.javaweb2015.services.CountryService;

@Service
public class CountryServiceImpl implements CountryService {

	@Inject
	private CountryDao dao;

	@Inject
	private CityService cityService;

	@Override
	public Country get(Integer id) {
		return dao.getById(id);
	}

	@Override
	public List<Country> getByField(SingularAttribute<Country, ?> attr, Object val) {
		return dao.getByField(attr, val);
	}

	@Override
	public List<Country> getAll() {
		return dao.getAll();
	}

	@Override
	public void createOrUpdate(Country country) {
		if (country.getId() == null) {
			dao.create(country);
		} else {
			dao.update(country);
		}
	}

	@Override
	public void delete(Country country) {
		dao.delete(country.getId());
	}

	@Override
	public void deleteAll() {
		dao.deleteAll();
	}

	@Override
	public Long getCount() {
		return dao.getCount();
	}

	@Override
	public List<Country> getAll(SingularAttribute<Country, ?> attr, boolean ascending, int startRecord, int pageSize) {
		return dao.getAll(attr, ascending, startRecord, pageSize);
	}

	@Override
	public void deleteWithRelations(Country country) {
		List<City> relatedCities = cityService.getByField(City_.country, country);
		for (City city : relatedCities) {
			cityService.deleteWithRelations(city);
		}
		delete(country);
	}

}
